Certain bitwise
operations are not needed and should not be performed because their results are predictable.
Specifically, using And -1
with any value always results in the original value.
That is because the binary representation of -1
on a numeric data type
supporting negative numbers, such as Integer
or Long
, is based on two’s complement and made of all 1s: &B111…111
.
Performing And
between a value and &B111…111
means applying the And
operator to each bit of the value
and the bit 1
, resulting in a value equal to the provided one, bit by bit.
anyValue And -1 ' Noncompliant
anyValue ' Compliant
Similarly, anyValue Or 0
always results in anyValue
, because the binary representation of 0
is always
&B000…000
and the Or
operator returns its first input when the second is 0
.
anyValue Or 0 ' Noncompliant
anyValue ' Compliant
The same applies to anyValue Xor 0
: the Xor
operator returns 1
when its two input bits are different
(1
and 0
or 0
and 1
) and returns 0
when its two input bits are the same (both
0
or both 1
). When Xor
is applied with 0
, the result would be 1
if the other input is
1
, because the two input bits are different, and 0
if the other input bit is 0
, because the two input are the
same. That results in returning anyValue
.
anyValue Xor 0 ' Noncompliant
anyValue ' Compliant